﻿using System;
using System.IO;
using System.Text;
using System.Web.Mvc;

namespace NiggleAmp.Web
{
    public static class ResourceIncludes
    {
        const string SCRIPTS_FILE = "NiggleAmp.Web.Scripts.NiggleAmp.script-includes.txt";

        const string STYLE_SHEETS_FILE = "NiggleAmp.Web.Content.CSS-includes.txt";

        public static MvcHtmlString Scripts(UrlHelper url)
        {
            return ResourceToHTML(
                SCRIPTS_FILE, 
                (builder, include) => 
                    builder.AppendFormat(
                        "<script type=\"text/javascript\" src=\"{0}\"></script>\r\n",
                        url.Content(string.Format("~/Scripts/NiggleAmp/{0}", include))
                    )
             );
        }

        public static MvcHtmlString StyleSheets(UrlHelper url)
        {
            return ResourceToHTML(
                STYLE_SHEETS_FILE,
                (builder, include) =>
                    builder.AppendFormat(
                        "<link href=\"{0}\" rel=\"stylesheet\" type=\"text/css\" />\r\n",
                        url.Content(string.Format("~/Content/{0}", include))
                    )
            );
        }

        private static MvcHtmlString ResourceToHTML(string resourceName, Action<StringBuilder, string> renderFunction)
        {
            var builder = new StringBuilder();
            
            using (var stream = typeof(ResourceIncludes).Assembly.GetManifestResourceStream(resourceName))
            {
                if (stream == null)
                {
                    return MvcHtmlString.Empty;
                }

                using (var includes = new StreamReader(stream))
                {
                    while (!includes.EndOfStream)
                    {
                        var include = includes.ReadLine();
                        if (!string.IsNullOrEmpty(include))
                        {
                            renderFunction(builder, include);
                        }
                    }
                }
            }

            return MvcHtmlString.Create(builder.ToString());
        }
    }
}